
// src-electron/main.js
const {app, BrowserWindow, dialog, ipcMain} = require('electron')
const {join} = require('path')
const Database = require('sqlite3').verbose()

// 屏蔽安全警告
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'

// 初始化数据库
const db = new Database.Database(join(app.getPath('userData'), 'resources.db'))

// 创建资源管理表
const createTableSQL = `  CREATE TABLE IF NOT EXISTS resources (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    projectName TEXT NOT NULL,
    type TEXT,
    ip TEXT,
    port TEXT,
    username TEXT,
    password TEXT,
    frontendDir TEXT,
    backendDir TEXT,
    startDate TEXT,
    remark TEXT
  )`

db.serialize(() => {
    db.run(createTableSQL)
})

// 创建浏览器窗口时，调用这个函数
const createWindow = ()=>{
    const win = new BrowserWindow({
        width: 1200,
        height: 800,
        title: 'electron-sqlite3',
        show: false, // 窗口创建时隐藏
        icon: join(__dirname, '../public/favicon.ico'),
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: join(__dirname, 'preload.js')
        }
    })
    win.setMenu( null);
    // development模式
    if(process.env.VITE_DEV_SERVER_URL){
        win.loadURL(process.env.VITE_DEV_SERVER_URL)
        // 开启调试台
        win.webContents.openDevTools()
    }else{
        win.loadFile(join(__dirname, '../dist/index.html'))
    }

    // 程序启动时 会出现短暂的白屏 所以窗口初始化完成后展示
    win.once('ready-to-show', () => {
        win.show(); // 窗口初始化完成后展示
    });

    // // 窗口关闭
    // win.on('close', (e) => {
    //     e.preventDefault()
    //     // 窗口关闭提示弹框
    //     win && dialog.showMessageBox(win, {
    //         type: 'info',
    //         title: '退出提示',
    //         message: '是否要退出electron-sqlite3？',
    //         buttons: ['Yes', 'No'],
    //         cancelId: 1,
    //     }).then((idx) => {
    //         if(idx.response != 1) {
    //             app.exit()
    //         }
    //     })
    // })
}

// IPC 处理程序
// 获取资源列表（分页查询）
ipcMain.handle('get-resources', async (event, params) => {
    const page = params.page || 1
    const pageSize = params.pageSize || 10
    const projectName = params.projectName || ''

    const offset = (page - 1) * pageSize
    let sql = 'SELECT * FROM resources'
    let countSql = 'SELECT COUNT(*) as total FROM resources'
    const sqlParams = []

    if (projectName) {
        sql += ' WHERE projectName LIKE ?'
        countSql += ' WHERE projectName LIKE ?'
        sqlParams.push(`%${projectName}%`)
    }

    sql += ' LIMIT ? OFFSET ?'
    sqlParams.push(pageSize, offset)

    // 使用 Promise 包装数据库操作
    const countPromise = new Promise((resolve, reject) => {
        db.get(countSql, projectName ? [`%${projectName}%`] : [], (err, row) => {
            if (err) {
                reject(err)
            } else {
                resolve(row.total)
            }
        })
    })

    const dataPromise = new Promise((resolve, reject) => {
        db.all(sql, sqlParams, (err, rows) => {
            if (err) {
                reject(err)
            } else {
                resolve(rows)
            }
        })
    })

    try {
        const [total, data] = await Promise.all([countPromise, dataPromise])

        // 返回简单对象，避免返回数据库相关的对象
        return {
            data: data.map(row => ({
                id: row.id,
                projectName: row.projectName,
                type: row.type,
                ip: row.ip,
                port: row.port,
                username: row.username,
                password: row.password,
                frontendDir: row.frontendDir,
                backendDir: row.backendDir,
                startDate: row.startDate,
                remark: row.remark
            })),
            total: total,
            page: page,
            pageSize: pageSize
        }
    } catch (error) {
        throw error
    }
})

// 添加资源
ipcMain.handle('add-resource', async (event, resource) => {
    const sql = `      INSERT INTO resources 
      (projectName, type, ip, port, username, password, frontendDir, backendDir, startDate, remark)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `
    const params = [
        resource.projectName,
        resource.type,
        resource.ip,
        resource.port,
        resource.username,
        resource.password,
        resource.frontendDir,
        resource.backendDir,
        resource.startDate,
        resource.remark
    ]

    return new Promise((resolve, reject) => {
        db.run(sql, params, function(err) {
            if (err) {
                reject(err)
            } else {
                // 返回简单对象
                resolve({
                    success: true,
                    id: this.lastID
                })
            }
        })
    })
})

// 更新资源
ipcMain.handle('update-resource', async (event, resource) => {
    const sql = `      UPDATE resources SET 
      projectName = ?, type = ?, ip = ?, port = ?, username = ?, 
      password = ?, frontendDir = ?, backendDir = ?, startDate = ?, remark = ?
      WHERE id = ?
    `
    const params = [
        resource.projectName,
        resource.type,
        resource.ip,
        resource.port,
        resource.username,
        resource.password,
        resource.frontendDir,
        resource.backendDir,
        resource.startDate,
        resource.remark,
        resource.id
    ]

    return new Promise((resolve, reject) => {
        db.run(sql, params, function(err) {
            if (err) {
                reject(err)
            } else {
                // 返回简单对象
                resolve({
                    success: true,
                    changes: this.changes
                })
            }
        })
    })
})

// 删除资源
ipcMain.handle('delete-resource', async (event, id) => {
    return new Promise((resolve, reject) => {
        db.run('DELETE FROM resources WHERE id = ?', [id], function(err) {
            if (err) {
                reject(err)
            } else {
                // 返回简单对象
                resolve({
                    success: true,
                    changes: this.changes
                })
            }
        })
    })
})

// electron 会在初始化后准备
app.whenReady().then(()=>{
    createWindow()
    app.on('activate', ()=>{
        if(BrowserWindow.getAllWindows().length === 0) createWindow()
    })
})

app.on('window-all-closed', ()=>{
    if(process.platform !== 'darwin') app.quit()
})

// 应用退出时关闭数据库
app.on('before-quit', () => {
    db.close()
})